package com.dattplace.controller;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;

import org.dozer.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.dattplace.model.Label;
import com.dattplace.model.ResultCode;
import com.dattplace.model.ResultData;
import com.dattplace.service.ILabelService;
import com.dattplace.util.RandomUtil;
import com.dattplace.util.StringUtil;
import com.dattplace.vo.LabelVo;
import com.dattplace.vo.SimpleModelVo;

@Controller
@Path("/label")
@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
public class LabelManagementController {
	
	@Autowired
	private ILabelService labelService;
	
	@Autowired
	private Mapper mapper;
	
	@Path("/saveLabel")
    @POST
    public ResultData<Object> saveLabel(final LabelVo labelVo,@Context HttpServletRequest req){
		
		try{
			// 判断是否存在
			if(StringUtil.isEmptyString(labelVo.getLabelName())){
				return ResultCode.error("标签名不能为空", null);
			}
			LabelVo label =labelService.queryLableByName(labelVo.getLabelName().trim());
			
			if(label!=null){
				return ResultCode.error("标签已经存在", null);
			}
			labelVo.setCreateDate(new Date());
			labelVo.setLabelId(new RandomUtil().getRandomId());
			return labelService.saveLabel(mapper.map(labelVo, Label.class));
			
		}catch (Exception e) {
			return ResultCode.error("新增标签失败", null);
		}
    }
	
	
	@Path("/{labelId}/deleteLabel")
    @GET
	public ResultData<Object> deleteLabel(@PathParam("labelId") final String labelId, @Context HttpServletRequest req) {
		try {
			labelService.deleteLabel(labelId);
			return ResultCode.success("删除标签成功", null);
		} catch (Exception e) {
			return ResultCode.error("删除标签失败", null);
		}
	}
	
	@Path("/queryLabelList")
    @GET
	public ResultData<Object> queryLabelList(
			@QueryParam("pageNo") final int pageNo,
			@QueryParam("pageSize") final int pageSize,
			@QueryParam("keyWord") final String keyWord,
			@Context HttpServletRequest req) {
    	try{
    		SimpleModelVo vo = new SimpleModelVo();
        	List<LabelVo> list =labelService.queryLabelList(pageNo,pageSize,keyWord);
            vo.setLabelList(list);
            vo.setCount(labelService.queryAllLabelCount(keyWord));
			return ResultCode.success("查询成功", vo);
    	}catch (Exception e) {
			return ResultCode.error("查询标签失败", null);
		}
    }

}
